package com.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tc.domain.Hospital_reimbursement_ratio;
import com.tc.domain.Insured_person;
import com.tc.dto.Insured_personDTO;
import com.tc.dto.Insured_personQueryDTO;
import com.tc.mapper.Insured_personMapper;
import com.tc.service.IHospital_reimbursement_ratioService;
import com.tc.service.IInsured_personService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tc.vo.Hospital_reimbursement_ratioVO;
import com.tc.vo.PageResultVO;
import com.tc.vo.PatientReimbursementRatioVO;
import com.tc.vo.Insured_personVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  被保险人服务实现类
 * </p>
 *
 * @author jcd
 * @since 2025-07-09
 */
@Service
public class Insured_personServiceImpl extends ServiceImpl<Insured_personMapper, Insured_person> implements IInsured_personService {

    @Autowired
    private IHospital_reimbursement_ratioService hospitalReimbursementRatioService;

    @Override
    public PageResultVO<Insured_personVO> pageQuery(Insured_personQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Insured_person> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加模糊查询条件
        if (StringUtils.hasText(queryDTO.getName())) {
            queryWrapper.like(Insured_person::getName, queryDTO.getName());
        }
        
        if (StringUtils.hasText(queryDTO.getIdCard())) {
            queryWrapper.like(Insured_person::getIdCard, queryDTO.getIdCard());
        }
        
        if (StringUtils.hasText(queryDTO.getHospitalNumber())) {
            queryWrapper.like(Insured_person::getHospitalNumber, queryDTO.getHospitalNumber());
        }
        
        if (StringUtils.hasText(queryDTO.getPaymentType())) {
            queryWrapper.eq(Insured_person::getPaymentType, queryDTO.getPaymentType());
        }
        
        if (StringUtils.hasText(queryDTO.getPersonCategory())) {
            queryWrapper.eq(Insured_person::getPersonCategory, queryDTO.getPersonCategory());
        }
        
        if (StringUtils.hasText(queryDTO.getHospitalLevel())) {
            queryWrapper.eq(Insured_person::getHospitalLevel, queryDTO.getHospitalLevel());
        }


        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Insured_person::getCreateTime);
        
        // 执行分页查询
        Page<Insured_person> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<Insured_person> resultPage = this.page(page, queryWrapper);
        
        // 将实体对象转换为视图对象
        List<Insured_personVO> records = resultPage.getRecords().stream()
                .map(Insured_personVO::fromEntity)
                .collect(Collectors.toList());
        
        // 使用PageResultVO的静态方法直接构建分页结果对象
        return PageResultVO.convert(resultPage, records);
    }

    @Override
    public Insured_personVO getInsuredPersonById(Long id) {
        Insured_person insuredPerson = this.getById(id);
        return Insured_personVO.fromEntity(insuredPerson);
    }

    @Override
    @Transactional
    public boolean addInsuredPerson(Insured_personDTO insuredPersonDTO) {
        Insured_person insuredPerson = new Insured_person();
        BeanUtils.copyProperties(insuredPersonDTO, insuredPerson);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        insuredPerson.setCreateTime(now);
        insuredPerson.setUpdateTime(now);
        insuredPerson.setDeleted(0); // 设置为未删除
        
        return this.save(insuredPerson);
    }

    @Override
    @Transactional
    public boolean updateInsuredPerson(Insured_personDTO insuredPersonDTO) {
        Insured_person insuredPerson = new Insured_person();
        BeanUtils.copyProperties(insuredPersonDTO, insuredPerson);
        
        // 设置更新时间
        insuredPerson.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(insuredPerson);
    }

    @Override
    @Transactional
    public boolean deleteInsuredPerson(Long id) {
        return this.removeById(id);
    }
    
    @Override
    public List<PatientReimbursementRatioVO> getReimbursementRatioByPatientId(Long patientId) {
        // 查询患者信息
        Insured_person insuredPerson = this.getById(patientId);
        if (insuredPerson == null || !StringUtils.hasText(insuredPerson.getPaymentType()) 
                || "自费".equals(insuredPerson.getPaymentType())) {
            // 如果患者不存在或不是医保患者，则返回空列表
            return new ArrayList<>();
        }
        
        // 查询医院等级对应的报销比例
        String hospitalLevel = insuredPerson.getHospitalLevel();
        String personType = insuredPerson.getPersonCategory();
        
        if (!StringUtils.hasText(hospitalLevel) || !StringUtils.hasText(personType)) {
            return new ArrayList<>();
        }
        
        // 查询符合条件的医院报销比例
        LambdaQueryWrapper<Hospital_reimbursement_ratio> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital_reimbursement_ratio::getHospitalLevel, hospitalLevel)
                .eq(Hospital_reimbursement_ratio::getPersonType, personType)
                .eq(Hospital_reimbursement_ratio::getStaus, "启用") // 只查询启用状态的
                .orderByAsc(Hospital_reimbursement_ratio::getCostMin);
        
        List<Hospital_reimbursement_ratio> ratioList = hospitalReimbursementRatioService.list(queryWrapper);
        
        // 转换为VO对象
        List<PatientReimbursementRatioVO> voList = new ArrayList<>();
        for (Hospital_reimbursement_ratio ratio : ratioList) {
            PatientReimbursementRatioVO vo = new PatientReimbursementRatioVO();
            vo.setPatientId(patientId);
            vo.setPatientName(insuredPerson.getName());
            vo.setIdCard(insuredPerson.getIdCard());
            vo.setHospitalLevel(hospitalLevel);
            vo.setPersonType(personType);
            vo.setReimbursementRatio(ratio.getReimbursementRatio());
            vo.setCostMin(ratio.getCostMin());
            vo.setCostMax(ratio.getCostMax());
            voList.add(vo);
        }
        
        return voList;
    }
    
//    @Override
//    public BigDecimal getReimbursementRatio(String hospitalLevel, String personType, BigDecimal cost) {
//        if (!StringUtils.hasText(hospitalLevel) || !StringUtils.hasText(personType) || cost == null) {
//            return BigDecimal.ZERO;
//        }
//
//        // 查询符合条件的医院报销比例
//        LambdaQueryWrapper<Hospital_reimbursement_ratio> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Hospital_reimbursement_ratio::getHospitalLevel, hospitalLevel)
//                .eq(Hospital_reimbursement_ratio::getPersonType, personType)
//                .eq(Hospital_reimbursement_ratio::getStaus, "启用") // 只查询启用状态的
//                .le(Hospital_reimbursement_ratio::getCostMin, cost)
//                .ge(Hospital_reimbursement_ratio::getCostMax, cost);
//
//        Hospital_reimbursement_ratio ratio = hospitalReimbursementRatioService.getOne(queryWrapper);
//
//        if (ratio != null) {
//
//
//            // 返回报销比例
//            return  ratio.getReimbursementRatio();
//        }
//
//        return BigDecimal.ZERO;
//    }

    @Override
    public Hospital_reimbursement_ratioVO getReimbursementRatio(String hospitalLevel, String personType, BigDecimal cost) {
        if (!StringUtils.hasText(hospitalLevel) || !StringUtils.hasText(personType) || cost == null) {
            return null;
        }

        LambdaQueryWrapper<Hospital_reimbursement_ratio> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital_reimbursement_ratio::getHospitalLevel, hospitalLevel)
                .eq(Hospital_reimbursement_ratio::getPersonType, personType)
                .eq(Hospital_reimbursement_ratio::getStaus, "启用")
                .le(Hospital_reimbursement_ratio::getCostMin, cost)
                .ge(Hospital_reimbursement_ratio::getCostMax, cost);

        Hospital_reimbursement_ratio ratio = hospitalReimbursementRatioService.getOne(queryWrapper);

        if (ratio != null) {
            Hospital_reimbursement_ratioVO vo = new Hospital_reimbursement_ratioVO();
            vo.setRatioId(ratio.getRatioId());
            vo.setHospitalLevel(ratio.getHospitalLevel());
            vo.setPersonType(ratio.getPersonType());
            vo.setCostMin(ratio.getCostMin());
            vo.setCostMax(ratio.getCostMax());
            vo.setStaus(ratio.getStaus());
            vo.setReimbursementRatio(ratio.getReimbursementRatio());
            vo.setUpdateTime(ratio.getUpdateTime());
            return vo;
        }

        return null;
    }
}
